package cn.itcast.bos.controller;

import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.domain.common.ResponseResult;
import cn.itcast.bos.service.FixedAreaService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.criteria.*;
import java.util.*;

/**
 * Created by Administrator on 2018/12/27.
 */

@RestController
@RequestMapping("/fixedArea")
public class FixedAreaController {

    // 注入Service
    @Autowired
    private FixedAreaService fixedAreaService;

    // 保存定区
    @RequestMapping("save")
    public ResponseResult save(FixedArea fixedArea) {
        // 调用业务层，保存定区
        try {
            fixedAreaService.save(fixedArea);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.FAIL();
        }

        return ResponseResult.SUCCESS();
    }

    // 分页查询
    @RequestMapping("pageQuery")
    public Map pageQuery(int page, int rows,FixedArea fixedArea) {
        // 构造Pageable
        Pageable pageable = new PageRequest(page - 1, rows);
        // 构造条件查询对象
        Specification<FixedArea> specification = new Specification<FixedArea>() {
            @Override
            public Predicate toPredicate(Root<FixedArea> root,
                                         CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<Predicate>();
                // 构造查询条件
                if (StringUtils.isNotBlank(fixedArea.getId())) {
                    // 根据 定区编号查询 等值
                    Predicate p1 = cb.equal(root.get("id").as(String.class),
                            fixedArea.getId());
                    list.add(p1);
                }
                if (StringUtils.isNotBlank(fixedArea.getCompany())) {
                    // 根据公司查询 模糊
                    Predicate p2 = cb.like(
                            root.get("company").as(String.class),
                            "%" + fixedArea.getCompany() + "%");
                    list.add(p2);
                }

                return cb.and(list.toArray(new Predicate[0]));
            }
        };
        // 调用业务层，查询数据
        Page<FixedArea> pageData = fixedAreaService.findPageData(specification,
                pageable);

        // 将返回page对象 转换datagrid需要格式
        Map<String, Object> result = new HashMap();
        result.put("total", pageData.getTotalElements());
        result.put("rows", pageData.getContent());

        return result;
    }

}
